<template>
	<div class="app-container">
		<div class="table-wrapper">
			<h4>供水设施易损性计算</h4>
			<el-form :inline="true" ref="queryRef" :rules="rules" label-position="right" :model="params"
				label-width="200px">
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="编号：" class="form-item" prop="code">
							<el-input v-model="params.code" placeholder="" :disabled="true" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="设防情况：" class="form-item" prop="intensity">
							<el-select v-model="params.intensity" placeholder="请选择" class="form-select"
                                :disabled="disabled" clearable>
                                <el-option v-for="item in optionList2" :label="item.dictItemName"
                                    :value="item.dictItemCode">
                                </el-option>
                            </el-select>
						</el-form-item>
					</el-col>
					<!-- <el-col :span="11">
						<el-form-item label="维护人：" class="form-item" prop="createUserName">
							<el-input v-model="params.createUserName" placeholder="" clearable />
						</el-form-item>
					</el-col> -->
				</el-row>
				<!-- <el-row justify="center">
					<el-col :span="11">
						<el-form-item label="维护人所属单位：" class="form-item" prop="orgName">
							<el-input v-model="params.orgName" placeholder="" clearable />
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="维护时间:" class="form-item" prop="createTime">
							<el-date-picker v-model="params.createTime" type="date" placeholder="选择日期">
							</el-date-picker>
						</el-form-item>
					</el-col>
				</el-row> -->
				<el-row justify="center">
					<el-col :span="11">
						<el-form-item label="钢筋类型：" class="form-item" prop="rebarType">
							<el-select v-model="params.rebarType" placeholder="请选择" class="form-select" :disabled="!!route.query.operateType"
								clearable>
								<el-option v-for="item in optionList1" :key="item.dictItemCode" :label="item.dictItemName"
									:value="item.dictItemCode">
								</el-option>
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="11">
						<el-form-item label="年代：" class="form-item" prop="year">
							<el-input v-model="params.year" placeholder="请输入" :disabled="disabled" clearable />
							<!-- <el-select v-model="params.year" placeholder="请选择" class="form-select" :disabled="disabled"
								clearable>
								<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select> -->
						</el-form-item>
					</el-col>
				</el-row>
				<el-row v-if="isAdd" justify="end">
					<el-form-item class="bottom-button">
						<el-button type="primary" @click="handleVerify" v-if="!route.query.id">验证</el-button>
						<!-- <el-button type="primary" @click="handleCalcAdd">新增</el-button> -->
						<!-- <el-button type="primary" @click="handleBrickModify">修改</el-button> -->
						<!-- <el-button type="primary" @click.prevent="handleCalcdelete">删除</el-button> -->
						<!-- <el-button type="primary" @click="showUploadDialog = true">参数导入</el-button> -->
						<el-button type="primary" @click="onCalc" v-if="route.query.id">计算</el-button>
						<el-button type="primary" @click="onSubmit" v-if="route.query.id">提交</el-button>
					</el-form-item>
				</el-row>
			</el-form>
			<!-- 数据导入弹框 -->
			<import-data v-if="showUploadDialog" v-model="showUploadDialog" ref="uploadDialog" :uploadUrl="uploadUrl"
				downloadFileName="供水设施易损性计算参数导入.xlsx" @importSuccess="onImport"></import-data>

			<el-form :inline="true" ref="tableRef" :rules="rules" label-position="right" :model="tableFormData">
				<h4>计算水池壁裂缝宽度并比对破坏程度</h4>
				<el-table class="listTables" ref="table1Ref" border :data="tableFormData.tableData" style="width: 100%"
					@selection-change="onSelectionChange" :cell-style="{ border: '1px solid #e5ebf7' }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<el-table-column type="selection" width="55" label="序号" />
					<el-table-column header-align="center" align="center">
						<template #header>
							<span class="color-red">b</span>截面宽度 (m)
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.sectionWidth`" :rules="rules.sectionWidth">
								<el-input v-model="scope.row.sectionWidth" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center">
						<template #header>
							<span class="color-red">h</span>截面高度(m)
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.sectionHeight`" :rules="rules.sectionHeight">
								<el-input v-model="scope.row.sectionHeight" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center">
						<template #header>
							<span class="color-red">Rf</span>混凝土抗裂强度
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.ruptureStrength`"
								:rules="rules.ruptureStrength">
								<el-input v-model="scope.row.ruptureStrength" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center">
						<template #header>
							<span class="color-red">M</span>计算截面的弯矩（N.m）
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.sectionBendingMoment`"
								:rules="rules.sectionBendingMoment">
								<el-input v-model="scope.row.sectionBendingMoment" :disabled="scope.row.disabled"
									size="small" type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="result1" header-align="center" align="center" width="350">
						<template #header>
							<span>裂缝间钢筋应变的不均匀系数</span>
							<!-- 公式 -->
							<MultilineFormula tagOffset="-6px" :option="[
								{ content: 'Ψ' },
								{ content: '=', margin: '0 8px' },
								{ content: '1.2' },
								{ content: '[' },

								{ content: '1-' },
								{
									rows: [
										[
											{ content: '0.235(1+2r', sub: '1' },
											{ content: '+' },
											{ content: '0.4r', super: '\'', sub: '1' },
											{ content: '）' },
											{ content: 'R', sub: 'f' },
											{ content: 'bh', super: '2' },
										],
										[{ content: 'M' }]
									]
								},
								{ content: ']' },
							]"></MultilineFormula>
						</template>
					</el-table-column>
					<el-table-column prop="steelStrain" header-align="center" align="center">
						<template #header>
							<Formula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'ε', sub: 'g' },
							]"></Formula>
							<span>裂缝截面处钢筋的应变</span>
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.steelStrain`" :rules="rules.steelStrain">
								<el-input v-model="scope.row.steelStrain" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="result2" header-align="center" align="center">
						<template #header>
							<!-- 公式 -->
							<Formula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'ε', sub: 'g' },
								{ content: '-', left: '-20px', top: '-13px' },
								{ content: '=', margin: '0 8px' },
								{ content: 'Ψ' },
								{ content: 'ε', sub: 'g' },
							]"></Formula>
						</template>
					</el-table-column>
				</el-table>

				<div class="calc" style="margin:20px auto;">
					<el-table class="listTables" ref="table2Ref" border :data="tableFormData.tableData" style="width: 100%"
						@selection-change="onSelectionChange" :cell-style="{ border: '1px solid #e5ebf7' }"
						:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
						<el-table-column type="selection" width="55" label="序号" />
						<el-table-column header-align="center" align="center">
							<template #header>
								<span class="color-red">d</span>受拉钢筋直径(m)
							</template>
							<template #default="scope">
								<el-form-item :prop="`tableData.${scope.$index}.diameterOfTensileReinforcement`"
									:rules="rules.diameterOfTensileReinforcement">
									<el-input v-model="scope.row.diameterOfTensileReinforcement"
										:disabled="scope.row.disabled" size="small" type="number"></el-input>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column header-align="center" align="center">
							<template #header>
								<span class="color-red">μ</span>配筋率(m)
							</template>
							<template #default="scope">
								<el-form-item :prop="`tableData.${scope.$index}.reinforcementRatio`"
									:rules="rules.reinforcementRatio">
									<el-input v-model="scope.row.reinforcementRatio" :disabled="scope.row.disabled"
										size="small" type="number"></el-input>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column header-align="center" align="center">
							<template #header>
								<span class="color-red">r1</span>截面形状有关的系数
							</template>
							<template #default="scope">
								<el-form-item :prop="`tableData.${scope.$index}.shapeFactor1`" :rules="rules.shapeFactor1">
									<el-input v-model="scope.row.shapeFactor1" :disabled="scope.row.disabled" size="small"
										type="number"></el-input>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column header-align="center" align="center">
							<template #header>
								<span class="color-red">r'1</span>截面形状有关的系数
							</template>
							<template #default="scope">
								<el-form-item :prop="`tableData.${scope.$index}.shapeFactor2`" :rules="rules.shapeFactor2">
									<el-input v-model="scope.row.shapeFactor2" :disabled="scope.row.disabled" size="small"
										type="number"></el-input>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column prop="result3" header-align="center" align="center">
							<template #header>
								<span class="color-red">V</span>与纵向受拉钢筋表面形状有关的系数
							</template>
						</el-table-column>
						<el-table-column prop="result4" header-align="center" align="center" width="280">
							<template #header>
								<span>平均裂缝间距</span>
								<!-- 公式 -->
								<MultilineFormula tagOffset="-6px" fontWeight="bold" display="block" :option="[
									{ content: 'L', sub: 'f' },
									{ content: '=', margin: '0 8px' },
									{ content: '[' },
									{ content: '6+0.06' },
									{
										rows: [
											[{ content: 'd' }],
											[{ content: 'μ' }]
										]
									},
									{ content: '(1+2r', sub: '1' },
									{ content: '+' },
									{ content: '0.4r', super: '\'', sub: '1' },
									{ content: '）' },
									{ content: ']' },
									{ content: 'v' },
								]"></MultilineFormula>
							</template>
						</el-table-column>
						<el-table-column prop="averageStrain" header-align="center" align="center" width="250">
							<template #header>
								<!-- 公式 -->
								<Formula tagOffset="-6px" fontWeight="bold" :option="[
									{ content: 'ε', sub: 'l' },
									{ content: '-', left: '-20px', top: '-8px' },
								]"></Formula>
								<span>钢筋水平处裂缝之间受拉混凝土的平均应变</span>
							</template>
							<template #default="scope">
								<el-form-item :prop="`tableData.${scope.$index}.averageStrain`"
									:rules="rules.averageStrain">
									<el-input v-model="scope.row.averageStrain" :disabled="scope.row.disabled" size="small"
										type="number"></el-input>
								</el-form-item>
							</template>
						</el-table-column>
						<el-table-column prop="result5" header-align="center" align="center">
							<template #header>
								<!-- 公式 -->
								<Formula tagOffset="-6px" fontWeight="bold" :option="[
									{ content: 'ε', sub: 'f' },
								]"></Formula>
								<span>钢筋的平均应变</span>
							</template>
						</el-table-column>
					</el-table>
				</div>

				<el-table class="listTables" ref="table3Ref" border :data="tableFormData.tableData" style="width: 100%"
					@selection-change="onSelectionChange" :cell-style="{ border: '1px solid #e5ebf7' }"
					:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
					<el-table-column type="selection" width="55" label="序号" />
					<el-table-column header-align="center" align="center">
						<template #header>
							<span class="color-red">Eg</span>钢筋的弹性模量
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.elasticModulus`" :rules="rules.elasticModulus">
								<el-input v-model="scope.row.elasticModulus" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="Ψ">
						<template #default="scope">
							{{ scope.row.result1 }}
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="Lf">
						<template #default="scope">
							{{ scope.row.result4 }}
						</template>
					</el-table-column>
					<el-table-column prop="result9" header-align="center" align="center" width="130">
						<template #header>
							<span>钢筋截面积</span>
							<MultilineFormula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'A', sub: 'g' },
								{ content: '=', margin: '0 8px' },
								{
									rows: [
										[{ content: '∏d', super: '2' }],
										[{ content: '4' }]
									]
								},
							]"></MultilineFormula>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="配筋到惯性轴的距离" width="160">
						<template #header>
							<span>配筋到惯性轴的距离</span>
							<Formula tagOffset="-6px" fontWeight="bold" display="block" :option="[
								{ content: 'h', sub: '0' },
							]"></Formula>
						</template>
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.distance`" :rules="rules.distance">

								<el-input v-model="scope.row.distance" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="result9" header-align="center" align="center">
						<template #header>
							<MultilineFormula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'σ', sub: 'g' },
								{ content: '=', margin: '0 8px' },
								{
									rows: [
										[{ content: 'M' }],
										[
											{ content: '0.87' },
											{ content: 'A', sub: 'g', },
											{ content: 'h', sub: '0', }
										]
									]
								}
							]"></MultilineFormula>
						</template>
					</el-table-column>
					<el-table-column prop="result10" header-align="center" align="center" width="200">
						<template #header>
							<MultilineFormula tagOffset="-6px" fontWeight="bold" :option="[
								{ content: 'δ', sub: 'fmax' },
								{ content: '=', margin: '0 8px' },
								{ content: '2.0Ψ' },
								{
									rows: [
										[{ content: 'σ', sub: 'g' }],
										[{ content: 'E', sub: 'g' },]
									]
								},
								{ content: 'L', sub: 'f' },
							]"></MultilineFormula>
						</template>
					</el-table-column>
					<el-table-column header-align="center" align="center" label="修正值">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.result10Correct`"
								:rules="rules.result10Correct">
								<el-input v-model="scope.row.result10Correct" :disabled="scope.row.disabled" size="small"
									type="number"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
					<el-table-column prop="disasterRateStateCorrect" header-align="center" align="center" label="破坏程度" />
					<el-table-column header-align="center" align="center" label="修正值">
						<template #default="scope">
							<el-form-item :prop="`tableData.${scope.$index}.disasterRateStateCorrect`"
								:rules="rules.disasterRateStateCorrect">
								<el-input v-model="scope.row.disasterRateStateCorrect" :disabled="scope.row.disabled"
									size="small"></el-input>
							</el-form-item>
						</template>
					</el-table-column>
				</el-table>
			</el-form>

			<!-- 版本查看 -->
			<GetVersion v-if="openDialog" v-model:open="openDialog" @recalculateVersion="recalculateVersion" type="2" />
			<el-dialog v-model="dialogVisible" @close="cancle" title="提示" width="500px">
				<p v-for="item in messageList">{{ item.label }}
					<el-popover placement="bottom" title="提示详情" :width="200" trigger="click">
						<template #reference>
							<span style="color: #107ce5;cursor: pointer;">提示详情</span>
						</template>
						<template #default>
							<p v-for="val in item.value">{{ val }}</p>
						</template>
					</el-popover>
				</p>
				<p>&nbsp;</p>
			</el-dialog>
		</div>
	</div>
</template>

<script setup>
import { reactive, ref, toRefs } from "vue";
import { ElMessageBox } from 'element-plus'
// 接口
import { getInfo } from '@/api/login'
import {
	getByIdAndType, // 查询
	saveWsfManageResult, // 保存
	calculationDamageDegree, // 计算
	importDamageDegreeUrl, // 参数导入
	recalculateWsf,//验证
	saveWsfResult,//重新计算
} from "@/api/lifelineVulnerAnalysis/lifelineVulnerAnalysis.js";
import { getValidDictItemsByDictCode } from "@/api/map/disasterDataManagement/lifelineSystemInfo.js";
// 公用方法
import { parseTime } from "@/utils/ruoyi.js";
// 引入公式组件
import Formula from '@/components/Formula';
import MultilineFormula from '@/components/Formula/multiline';
import GetVersion from '../underPipeNet/dataFile/Version.vue';
// 引入导入弹框
import ImportData from "@/components/ImportData";

// 引入store
import useUserStore from '@/store/modules/user';
import useDictStore from '@/store/modules/dict';
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 用户名
const userName = computed(() => userStore.name || '');
// 所属机构名称
const orgName = computed(() => userStore.orgName || '');

// 当前实例
const { proxy } = getCurrentInstance();
// 当前路由
const route = useRoute();
const router = useRouter();

// 打开类型，query为查看
let operateType = computed(() => route.query.operateType || false);
// 是否是新增页，有路由参数是详情页，否则是新增页
let isAdd = computed(() => (route.query.id && route.query.operateType ? false : true));
// 禁用
const disabled = ref(false);

//最多保留N小数 ,N 在 options {decimals: N} 中定义
const positivedecimals = (rule, value, callback) => {
	value = String(value);
	if (
		value.indexOf(".") != -1 &&
		(value.split(".").length > rule.options.decimals ||
			value.split(".")[0] === "" ||
			value.split(".")[1] === "")
	) {
		callback(new Error()); //防止输入多个小数点
	} else if (
		value.indexOf(".") != -1 &&
		value.split(".")[1].length > rule.options.decimals
	) {
		callback(new Error()); //小数点后两位
	} else {
		callback();
	}
};
//验证是否yyyy年份（非必填）
const isYearNotMust = (rule, value, callback) => {
  if (value == '' || value == undefined || value == null) {
    callback();
  } else if (isNaN(Number(value))) {
    callback(new Error('请输入yyyy格式如2022'));
  } else if (value.toString().length!=4) {
    callback(new Error('请输入yyyy格式如2022'));
  } else if (value.toString().indexOf(".")!=-1) {
    callback(new Error('请输入yyyy格式如2022'));
  } else {
    callback();
  }
}
const data = reactive({
	// 表单参数
	params: {
		cpwedId: "", //id
		projectId: "",
		cpwedCode: "",
		code: "",//编号
		rebarType: "",//钢筋类型
		year: "",//年代
		intensity: "", //设防情况
		createTime: parseTime(new Date()), //维护时间
		createUserName: userName.value, //维护人
		orgName: orgName.value, //维护人所属单位
	},
	// 表单验证规则
	rules: {
		intensity: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		rebarType: [
			{ required: true, message: '请选择', trigger: 'change' }
		],
		year:  [{
				required: true,
				message: "请输入正确数值",
				validator: isYearNotMust,
				trigger: ["change", "blur"],
			}],
		sectionWidth: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		sectionHeight: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		ruptureStrength: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		sectionBendingMoment: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],

		diameterOfTensileReinforcement: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		reinforcementRatio: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		shapeFactor1: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		shapeFactor2: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		elasticModulus: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		unevenRatio: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		avgCrackSpacing: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		sectionalArea: [
			{ required: false, message: "", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		distance: [
			{ required: true, message: "请输入", trigger: "blur" },
			{
				message: "请输入正确数值，最多保留四位小数",
				validator: positivedecimals,
				options: { decimals: 4 },
				trigger: ["change", "blur"],
			},
		],
		// result10Correct: [
		//     { required: true, message: "请输入", trigger: "blur" },
		//     {
		//         message: "请输入正确数值，最多保留四位小数",
		//         validator: positivedecimals,
		//         options: { decimals: 4 },
		//         trigger: ["change", "blur"],
		//     },
		// ],
		// disasterRateStateCorrect: [
		//     { required: true, message: "请输入", trigger: "blur" },
		//     {
		//         message: "请输入正确数值，最多保留四位小数",
		//         validator: positivedecimals,
		//         options: { decimals: 4 },
		//         trigger: ["change", "blur"],
		//     },
		// ]
	},
	//钢筋类型，候选值为：对螺纹和人字纹钢筋、对光面钢筋、对冷拉低碳钢丝
	rebarTypeOptions: dictStore.rebarTypeOptions || [],
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 年份
	yearsOptions: dictStore.yearsOptions1 || [],
	// 表格数据
	tableFormData: {
		tableData: [],
	},
	// 表格选中行
	multipleSelection: [],
});
const {
	params,
	fortificationOptions,
	yearsOptions,
	rebarTypeOptions,
	rules,
	tableFormData,
	multipleSelection,
} = toRefs(data);

//表格
const table1Ref = ref();
const table2Ref = ref();
const table3Ref = ref();
// 表格行选中
const onSelectionChange = (val) => {
	multipleSelection.value = val;
}

// 导入弹框是否显示
let showUploadDialog = ref(false);
// 导入数据接口路径
const uploadUrl = ref(importDamageDegreeUrl);
// 导入成功回调
const onImport = (response, uploadFile, uploadFiles) => {
	const { code, data } = response;
	if (code == 200 && data) {
		proxy.$modal.msgSuccess('导入数据成功!');
		// 列表数据回显
		tableFormData.value.tableData = [...data];
	}
}
//计算水池壁裂缝宽度并比对破坏程度
const onCalc = () => {
	proxy.$refs['queryRef'].validate((valid, fields) => {
		if (valid) {
			let formData = tableFormData.value.tableData[0];
			let query = {
				id: formData.id,
				rebarType: params.value.rebarType,
				sectionWidth: formData.sectionWidth,
				sectionHeight: formData.sectionHeight,
				ruptureStrength: formData.ruptureStrength,
				sectionBendingMoment: formData.sectionBendingMoment,
				steelStrain: formData.steelStrain,
				diameterOfTensileReinforcement: formData.diameterOfTensileReinforcement,
				reinforcementRatio: formData.reinforcementRatio,
				shapeFactor1: formData.shapeFactor1,
				shapeFactor2: formData.shapeFactor2,
				averageStrain: formData.averageStrain,
				elasticModulus: formData.elasticModulus,
				distance: formData.distance,
				disasterRateState: formData.disasterRateState,
				disasterRateStateCorrect: formData.disasterRateStateCorrect,
				height: formData.height,
				result1: formData.result1,
				result2: formData.result2,
				result3: formData.result3,
				result4: formData.result4,
				result5: formData.result5,
				result6: formData.result6,
				result7: formData.result7,
				result8: formData.result8,
				result9: formData.result9,
				result10: formData.result10,
				result10Correct: formData.result10Correct,
				ids: formData.ids,
			}
			proxy.$modal.loading('正在努力计算,请耐心等待！');
			calculationDamageDegree(query).then((res) => {
				proxy.$modal.closeLoading();
				const { code, data } = res;
				if (code === 200 && data) {
					// 表格数据回显
					tableFormData.value.tableData = [{ ...tableFormData.value.tableData[0], ...data }];
					proxy.$modal.msgSuccess('计算完成！计算结果未保存，若需保存结果，请计算后点击提交按钮！');
				}
			}).catch(err => {
				proxy.$modal.closeLoading();
				console.log(err.message);
			});
		} else {
			proxy.$refs['queryRef'].scrollToField(Object.keys(fields)[0]);
		}
	})
};
// 显示弹框
const openDialog = ref(false)
const handleVerify = () => {
	openDialog.value = true;
}
// 验证
const messageList = ref([]);
const dialogVisible = ref(false);
const cancle = () => {
	dialogVisible.value = false;
}
const recalculateVersion = (version) => {
	openDialog.value = false;
	recalculateWsf({ versionId:version.id, type: '2' }).then(res => {
		if (JSON.stringify(res.data) == '{}') {
			ElMessageBox.confirm(
				'数据通过验证，是否计算？', '提示',
				{
					confirmButtonText: '计算并保存',
					cancelButtonText: '取消',
					type: 'success',
				}
			)
				.then(() => {
					saveWsfResult({ versionId:version.id }).then(response => {
						if (response.code == 200) {
							router.push(`/lifelineVulnerAnalysis/lifelineMain?type=2`)
						}
					})
				}).catch(() => { })
		} else {
			const { data } = res;
			messageList.value = [];
			for (let i in data) {
				messageList.value.push({ label: `第${i}行计算参数未填写完整，请补充完整再计算。`, value: data[i] })
			}
			dialogVisible.value = true;
		}
	})
}
// 保存
const onSubmit = () => {
	proxy.$refs['queryRef'].validate((valid, fields) => {
		if (valid) {
			let formData = tableFormData.value.tableData[0];
			let query = {
				type:'2',
				waterSupplyParam: {
					id: formData.id,
					rebarType: params.value.rebarType,
					sectionWidth: formData.sectionWidth,
					sectionHeight: formData.sectionHeight,
					ruptureStrength: formData.ruptureStrength,
					sectionBendingMoment: formData.sectionBendingMoment,
					steelStrain: formData.steelStrain,
					diameterOfTensileReinforcement: formData.diameterOfTensileReinforcement,
					reinforcementRatio: formData.reinforcementRatio,
					shapeFactor1: formData.shapeFactor1,
					shapeFactor2: formData.shapeFactor2,
					averageStrain: formData.averageStrain,
					elasticModulus: formData.elasticModulus,
					distance: formData.distance,
					disasterRateState: formData.disasterRateState,
					disasterRateStateCorrect: formData.disasterRateStateCorrect,
					height: formData.height,
					result1: formData.result1,
					result2: formData.result2,
					result3: formData.result3,
					result4: formData.result4,
					result5: formData.result5,
					result6: formData.result6,
					result7: formData.result7,
					result8: formData.result8,
					result9: formData.result9,
					result10: formData.result10,
					result10Correct: formData.result10Correct,
					ids: formData.ids?formData.ids:'',
				}
			}
			saveWsfManageResult(query).then((res) => {
				const { code, data } = res;
				if (code === 200) {
					proxy.$modal.msgSuccess("保存成功！");
					// 延迟跳转
					setTimeout(() => {
						router.push('/lifelineVulnerAnalysis/lifelineMain')
					}, 1500)
				}
			}).catch(err => {
				console.log(err.message);
			});
		} else {
			proxy.$refs['queryRef'].scrollToField(Object.keys(fields)[0]);
		}
	})
}

//字典表查询
const optionList1 = ref([])
const optionList2 = ref([])
const optionList3 = ref([])
/** 获取字典值 */
async function getDictData() {
	await getValidDictItemsByDictCode("smxgsgjlx").then(response => {
		optionList1.value = response.data;//钢筋类型
	});
	await getValidDictItemsByDictCode("smxsfqk").then(response => {
		optionList2.value = response.data;//设防情况
	});
	await getValidDictItemsByDictCode("smxjsnd").then(response => {
		optionList3.value = response.data;//建造年代
	});
}
getDictData();
// 获取数据
function getData(parmas) {
	getByIdAndType(parmas).then((res) => {
		const { code, data } = res;
		if (code === 200 && data) {
			const { waterSupplyVo, tableEntity } = data;
			if (waterSupplyVo) {
				// 基础信息
				params.value.code = tableEntity.code;
				params.value.intensity = waterSupplyVo.intensity;
				params.value.year = waterSupplyVo.year;
				params.value.rebarType = waterSupplyVo.rebarType;
				// 维护时间
				const dateTime = new Date()
				params.value.createTime = parseTime(dateTime);
				// 根据id获取用户信息
				params.value.createUserName = userStore.name;
				params.value.orgName = userStore.orgName;
				// getUserInfo(tableEntity.createUser);
				//循环遍历之前加上非空判断
				tableFormData.value.tableData = [{ ...waterSupplyVo, disabled: operateType.value === 'query' ? true : false }]
			}
		}
	}).catch(err => {
		console.log(err);
	});
}

// 挂载
onMounted(() => {
	const id = route.query.id;
	if (id) {
		disabled.value = true;
		// 获取数据
		getData({ id, type: 2 });
	} else {
		disabled.value = false;
	}
});
</script>

<style lang="scss" scoped>
.table-wrapper {
	position: relative;

	h4 {
		font-size: 16px;
		font-weight: bold;
		color: #107ce5;
		text-align: center;
	}

	// 字体红色
	.color-red {
		color: red !important;
	}
}
</style>